package com.mm.config;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 延迟队列  订单30分钟后自动取消
 */
@Configuration
@Slf4j
public class DelayRabbitConfig {

    //绑定键
    public final static String ORDER_DELAY = "order.delay";
    public final static String ORDER_RELEASE = "order.release";
    public final static String ORDER_EXCHANGE = "order-exchange";

    @RabbitListener(queues = DelayRabbitConfig.ORDER_RELEASE)
    public void message(String ms, Message message, Channel channel){
        log.info(ms + "订单已取消");
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Bean
    public Queue orderDelay(){
        Map<String,Object> arguments = new HashMap<>();
        /**
         * x-dead-letter-exchange: order-event-exchange
         * x-dead-letter-routing-key: order.release.order
         * x-message-ttl: 60000
         */
        arguments.put("x-dead-letter-exchange",ORDER_EXCHANGE);
        arguments.put("x-dead-letter-routing-key",ORDER_RELEASE);
        arguments.put("x-message-ttl",60000);
        return new Queue(ORDER_DELAY,true,false,false,arguments);
    }

    @Bean
    public Queue orderRelease(){
        return new Queue(ORDER_RELEASE,true,false,false);
    }

    @Bean
    TopicExchange orderExchange(){
        return  new TopicExchange(ORDER_EXCHANGE);
    }

    //将man和topicExchange绑定,而且绑定的键值为topic.man
    //这样只要是消息携带的路由键是topic.man,才会分发到该队列
    @Bean
    Binding bindingOrderDelayExchangeMessage() {
        return BindingBuilder.bind(orderDelay()).to(orderExchange()).with(ORDER_DELAY);
    }

    //将women和topicExchange绑定,而且绑定的键值为用上通配路由键规则topic.#
    // 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列
    @Bean
    Binding bindingOrderReleaseExchangeMessage2() {
        return BindingBuilder.bind(orderRelease()).to(orderExchange()).with(ORDER_RELEASE);
    }


}
